package com.nl.controller.xuyi.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.model.BaseResult;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.mapper.SmsUserMapper;
import com.nl.controller.xuyi.bean.MgrRelYwReq;
import com.nl.controller.xuyi.bean.XuYiCheckInfoBo;
import com.nl.controller.xuyi.bean.pocbo.QryYunWeiListDispatcher;
import com.nl.controller.xuyi.mapper.XuYiCheckMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.nl.controller.common.model.Response;
import com.nl.controller.common.util.ResponseUtil;
import com.nl.controller.web.bean.SmsMgrTemplateInfo;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.service.LoginService;
import com.nl.controller.web.service.SmsMgrTemplateInfoService;
import com.nl.controller.web.service.SmsUserService;
import com.nl.controller.xuyi.service.XuYiMgrTemplateService;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequestMapping("/xuYiMgr")
@RestController
@Validated
public class XuYiMgrTemplateController {

	@Autowired
	XuYiMgrTemplateService xuYiMgrTemplateService;

	@Autowired
	private SmsMgrTemplateInfoService smsMgrTemplateInfoService;

	@Autowired
	private SmsUserService smsUserService;

	@Autowired
	private LoginService loginService;

	@Autowired
	private CommonService commonService;

	@Autowired
	private XuYiCheckMapper xuYiCheckMapper;

	@Autowired
	private SmsUserMapper smsUserMapper;



	@ApiOperation(value = "根据项目名称查询项目详情", notes = "根据项目名称查询项目详情")
	@PostMapping("findMgrTemplateByName")
	public Response findMgrTemplate(
			@RequestParam(value = "mgrName", required = false) String mgrName,
			 @RequestParam Map<String, Object> paramMap) {
		log.info("根据项目名称查询项目详情：{}", paramMap.toString());

		List<SmsMgrTemplateInfo> mgrTemplateList = xuYiMgrTemplateService.findMgrTemplateByName(mgrName);

		log.info("根据项目名称查询项目详情结果：{}", mgrTemplateList);
		return ResponseUtil.sucess(mgrTemplateList);
	}

	@ApiOperation(value = "根据项目编码查询名称项目详情", notes = "根据项目编码查询名称项目详情")
	@PostMapping("findMgrTemplateById")
	public Response findMgrTemplateById(
			@RequestParam(value = "mgrId", required = false) String mgrId,
			 @RequestParam Map<String, Object> paramMap) {
		log.info("根据项目编码查询名称项目详情：{}", paramMap.toString());

		SmsMgrTemplateInfo mgrTemplate = xuYiMgrTemplateService.findMgrTemplateById(mgrId);

		log.info("根据项目名称查询项目详情结果：{}", mgrTemplate);
		return ResponseUtil.sucess(mgrTemplate);
	}


	@ApiOperation(value = "变更项目发送内容", notes = "变更项目发送内容")
	@PostMapping("modifyContent")
	public Response modifyContent(
			@RequestParam(value = "mgrId", required = false) String mgrId,
			@RequestParam(value = "content", required = false) String content,
			@RequestParam(value = "contentType", required = false) String contentType,
			HttpSession session,@RequestParam Map<String, Object> paramMap) {
		log.info("根据项目编码查询名称项目详情：{}", paramMap.toString());
		SmsUsers user = (SmsUsers) session.getAttribute("user");

		SmsMgrTemplateInfo smsMgrTemplateInfo;

		smsMgrTemplateInfo = smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId);

		int result = 0;
		//自定义短信内容，入审核表，发送审核短信。
		if("0".equals(contentType)){
			XuYiCheckInfoBo xuYiCheckInfoBo = new XuYiCheckInfoBo();
			xuYiCheckInfoBo.setMgrId(mgrId);
			xuYiCheckInfoBo.setMgrContent(content);
			xuYiCheckInfoBo.setMgrContentType(contentType);
			xuYiCheckInfoBo.setType("5");
			xuYiCheckInfoBo.setCheckState("0");
			xuYiCheckInfoBo.setCheckNumber("0");
			xuYiCheckInfoBo.setOperator(user.getMsisdn());
			//入项目短信内容审核表
			result = xuYiCheckMapper.addConTempCheckInfo(xuYiCheckInfoBo);
			//入表成功发送审核短信
			if(result > 0){
				int checkNum = 1;
				checkNum = Integer.parseUnsignedInt(smsMgrTemplateInfo.getCheckNum())+1;
				StringBuffer sbf = new StringBuffer();
				//String contents = "【江苏省应急平台】盱眙供电局项目:" + smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId).getName()+"，项目编码为:"+mgrId+"+"+checkNum+ "，已完成配置，请审核，";
				String contents = "【江苏省应急平台】您好，盱眙供电局项目:" + smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId).getName()+"，项目编码为:"+mgrId+"，已完成配置，请审核，";
				sbf.append(contents);
				if (!user.getDuty().equals("99")) {
					if (!(content).equals(smsMgrTemplateInfo.getContent())) {
						sbf.append("改动项:");
						sbf.append("短信内容改为:"+content+",原先:"+smsMgrTemplateInfo.getContent());
						sbf.append("，审核通过请回复\'Y-"+mgrId+"+"+checkNum+"-XYGD\'");
						sbf.append("，审核不通过请回复\'N-"+mgrId+"+"+checkNum+"-XYGD\'。");
						List<SmsUsers> smsUsers = smsUserService.findCityUsersbyCityId("12");
						if (null!= smsUsers && !smsUsers.isEmpty()) {
							for (SmsUsers smsUser : smsUsers) {
								loginService.sendCode(smsUser.getMsisdn(),sbf.toString());
								log.info("手机号" + smsUser.getMsisdn());
								log.info(sbf.toString());
							}
						}
					}
				}
			}
			//更改项目状态为停止，审核状态为待审核
			int modifyStateResult = smsMgrTemplateInfoService.modifyMgrState(mgrId, "12", "2", "0");
			if(modifyStateResult>0){
				log.info("项目："+mgrId+"内容发生变更，内容为自定义内容，已经出发审核短信，项目状态变更成功");
			}else{
				log.info("项目："+mgrId+"内容发生变更，内容为自定义内容，已经出发审核短信，项目状态变更失败");
			}
		}else{
			//模板短信，无需审核，直接入表。
			//直接修改短信模板
			result = xuYiMgrTemplateService.modifyContent(mgrId,content,contentType);
			//更改项目状态为停止，审核状态为待审核
			int modifyStateResult = smsMgrTemplateInfoService.modifyMgrState(mgrId, "12", "2", "2");
			if(modifyStateResult>0){
				log.info("项目："+mgrId+"内容发生变更，内容为短信模板内容，不触发审核，项目状态变更成功");
			}else{
				log.info("项目："+mgrId+"内容发生变更，内容为短信模板内容，不触发审核，项目状态变更失败");
			}
			//使用短信模板，无需发送审核短信，通知系统管理员即可。
			String content2 = "【江苏省应急平台】您好，项目:" + smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId).getName()+"，项目编码为："+mgrId+"，由"+user.getMsisdn()+"变更，项目短信内容为："+content+"，该项目使用供电局短信模板，无需审核，请悉知。";
			//通知系统管理员
			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("duty", "0");
			List<SmsUsers> provinceUsers = smsUserMapper.findUser(map2);
			for (SmsUsers smsUsers : provinceUsers) {
				loginService.sendCode(smsUsers.getMsisdn(),content2);
			}
		}

		commonService.createSmsOperLog("3", "变更项目内容【"+mgrId+"】", "0", "项目维护管理");



		log.info("变更项目短信内容结果：{}", result);
		return ResponseUtil.sucess(result);
	}

	@PostMapping("configureXuYiMgr")
	public Response configureMgrTemplate(
			@RequestParam(value = "cityId", required = false) String cityId,
			@RequestParam(value = "countyId", required = false) String countyId,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "extId", required = false) String extId,
			@RequestParam(value = "startTime", required = false) String startTime,
			@RequestParam(value = "endTime", required = false) String endTime,
			@RequestParam(value = "isLocal", required = false) String isLocal,
			@RequestParam(value = "threshold", required = false) int threshold,
			@RequestParam(value = "isThreshold", required = false) String isThreshold,
			@RequestParam(value = "mgrId", required = false) String mgrId,
			@RequestParam(value = "regionId", required = false) String regionId,
			@RequestParam(value = "regionType", required = false) String regionType,
			@RequestParam(value = "regionTypeValue", required = false) String regionTypeValue,
			@RequestParam(value = "reset", required = false) String reset,
			@RequestParam(value = "cycle", required = false) String cycle,
			@RequestParam(value = "cycleThreshold", required = false) String cycleThreshold,
			@RequestParam(value = "localDate", required = false) String localDate,
			@RequestParam(value = "mgrFlag", required = false) String mgrFlag,
			HttpSession session, @RequestParam Map<String, Object> paramMap) {
		log.info("插入项目模板参数：{}", paramMap.toString());
		SmsUsers user = (SmsUsers) session.getAttribute("user");
		String cityName = smsMgrTemplateInfoService.findCityName(cityId);
		String mgrState = "3";//开启
		String templateState = "0";//审核通过
		log.info(startTime+endTime);
//		if (user.getDuty().equals("0")) {
//			//mgrState = "0";
//			templateState="2";
//		}
		int checkNum = 1;
		int result = 0;
		//参数处理
		log.info("根据城市查询扩展码信息参数：{}", cityId);
		List<String> list = new ArrayList<>();
		if (cityId != null && !"undefined".equals(cityId) && cityId != "") {
			list = smsUserService.findExtIdByCityId(cityId);
		}
		SmsMgrTemplateInfo smsMgrTemplateInfo;
		extId = list.get(0);
		log.debug("根据城市查询扩展码信息返回数据：{}", list.size());
		result = xuYiMgrTemplateService.configureMgrTemplate(cityId,countyId,name,extId,startTime,endTime,isLocal,
				threshold,isThreshold,mgrId,regionId,regionType,regionTypeValue,
				user.getMsisdn(),cycle,cycleThreshold,localDate,checkNum,mgrFlag);
		log.debug("插入项目模板表返回参数：{}", result);
		if (result == 1) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("mgrId", mgrId);
			map.put("reset", reset);
			smsMgrTemplateInfoService.resetThreshold(map);
			return ResponseUtil.sucess("修改成功");
		} else {
			log.debug("插入项目模板表返回参数：{}", result);
			return ResponseUtil.error(result, "插入项目模板表失败，请重试");
		}
	}

	@PostMapping("addMgrYunWei")
	public BaseResult addMgrYunWei(
			@Validated @RequestBody MgrRelYwReq mgrRelYwReq, BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			throw new SmsException(bindingResult.getFieldError().getDefaultMessage());
		}
		if(!StringUtils.isEmpty(mgrRelYwReq.getYunWeiUids())) {
			List<String> uidList = JSON.parseArray(mgrRelYwReq.getYunWeiUids(), String.class);
			mgrRelYwReq.setUidsList(uidList);
		}
		log.info("插入项目与运维人员关联表：{}", mgrRelYwReq.toString());
		BaseResult insertResult = xuYiMgrTemplateService.addMgrYunWei(mgrRelYwReq);
		log.info("插入项目与运维人员关联表结果：{}", insertResult);
		return insertResult;
	}

	@PostMapping("findYWByMgrId")
	public BaseResult<List<QryYunWeiListDispatcher>> findYWByMgrId(
			@RequestParam(value = "mgrId", required = false) String mgrId,
			@RequestParam Map<String, Object> paramMap
	) {
		log.info("通过项目编码查询关联的运维人员：{}", paramMap.toString());
		BaseResult<List<QryYunWeiListDispatcher>> yunweiList  = xuYiMgrTemplateService.findYWByMgrId(mgrId);
		log.info("插入项目与运维人员关联表结果：{}", yunweiList);
		return yunweiList;
	}

}
